package com.itheima.service.Impl;

import com.alibaba.fastjson.JSON;
import com.itheima.domain.Product;
import com.itheima.mapper.ProductMapper;
import com.itheima.service.ProductService;
import org.apache.dubbo.config.annotation.DubboService;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private RestHighLevelClient client;

    /**
     * 搜索商品信息
     * @param searchString 搜索条件
     * @return 搜索结果
     */
    @Override
    public List<Product> search(String searchString) {
        //从索引中查询
        List<Product> list = null;
        try {
            //2.创建查询请求对象
            SearchRequest searchRequest = new SearchRequest();
            //4.创建查询条件构建器
            SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
            //6.创建查询条件
            QueryBuilder queryBuilder= QueryBuilders.matchQuery("title",searchString);
            //6.1创建高亮条件
            HighlightBuilder highlightBuilder=new HighlightBuilder()
                    .field("title").preTags("<font color='red'>")
                    .postTags("</font>");
            //5.添加查询条件
            sourceBuilder.query(queryBuilder).highlighter(highlightBuilder)
                    .from(0).size(500);
            //3.添加查询条件构建器
            searchRequest.source(sourceBuilder);
            //1.开始执行查询
            SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
            //7.处理查询结果并将高亮内容设置给product的title属性
            SearchHit[] hits = response.getHits().getHits();
            list = Arrays.stream(hits).map(hit -> {
                //获取_source中的原始数据内容
                Product product = JSON.parseObject(hit.getSourceAsString(), Product.class);
                //获取"highlight"高亮内容
                String title = hit.getHighlightFields().get("title").fragments()[0].toString();
                //将高亮的title设置到good中并返回
                product.setTitle(title);
                return product;
            }).collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 添加商品信息
     * @param product 商品对象
     */
    @Override
    public void add(Product product) {
        //需求:在添加商品信息是，除了将商品信息保存到MySQL中之外，还需要将商品信息保存到ES中

        //1. 向mysql中添加商品信息
        productMapper.add(product);

        //2.向es中添加商品信息,创建文档

        try {
            //2.2 创建请求对象,指定要保存到的索引库
            IndexRequest indexRequest = new IndexRequest("j_product");
            //2.3 向请求中添加要保存的数据
            indexRequest.id(String.valueOf(product.getId()))
                    .source(JSON.toJSONString(product), XContentType.JSON);
            //2.1 开始发送请求,创建文档
            IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
            //2.4控制台打印响应的结果
            System.out.println(response.status());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public List<Product> findAll() {
        List<Product> list=productMapper.findAll();
        return list;
    }
}
